package com.ita.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ita.po.Department;
import com.ita.po.People;

public class Util {

	public static void main(String[] args) throws ParseException {
		String test = "A-P pname:tmac,birthday:2012-12-06,salary:1000.0,tel:13631223783,dept_id:8";
		People p = strToPeople(test);

		System.out.println(p.getPname());
		String test2 = "A-D dname:it,city:hk";
		System.out.println(strToDepartment(test2).getDname());

	}

	public static People strToPeople(String str) throws ParseException {
		String[] a2 = str.split(",");// id:pid
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		int id = 0;
		String pname = null;
		String birthday = null;
		float salary = -1;
		String tel = null;
		Date birth = null;
		int deptId = -1;
		for (int i = 0; i < a2.length; i++) {
			if (a2[i].startsWith("id")) {
				id = Integer.parseInt(a2[i].replace("id:", ""));
			} else if (a2[i].startsWith("pname")) {
				pname = a2[i].replace("pname:", "");
			} else if (a2[i].startsWith("birthday")) {
				birthday = a2[i].replace("birthday:", "");
			} else if (a2[i].startsWith("salary")) {
				salary = Float.parseFloat(a2[i].replace("salary:", ""));
			} else if (a2[i].startsWith("tel")) {
				tel = a2[i].replace("tel:", "");
			} else if (a2[i].startsWith("dept_id")) {
				deptId = Integer.parseInt(a2[i].replace("dept_id:", ""));
			}
		}
		if (birthday != null) {
			birth = stringToDate(birthday);
		}
		People p = new People();
		p.setId(id);
		p.setPname(pname);
		p.setBirthday(birth);
		p.setSalary(salary);
		p.setTel(tel);
		p.setDeptId(deptId);
		// System.out.println(id + "...." + pname + "...." + salary + "...." +
		// tel + "...." + deptId+".."+birth);

		return p;
	}

	public static Department strToDepartment(String str) {
		String[] a2 = str.split(",");// id:pid
		int deptId = 0;
		String dname = null;
		String city = null;
		for (int i = 0; i < a2.length; i++) {
			if (a2[i].startsWith("dept_id")) {
				deptId = Integer.parseInt(a2[i].replace("dept_id:", ""));
			} else if (a2[i].startsWith("dname")) {
				dname = a2[i].replace("dname:", "");
			} else if (a2[i].startsWith("city")) {
				city = a2[i].replace("city:", "");
			}
		}

		Department d = new Department();
		d.setDeptId(deptId);
		d.setDname(dname);
		d.setCity(city);
		// System.out.println(deptId + "...." + dname + "...." + city );
		return d;
	}

	private static Date stringToDate(String str) {
		Date date = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

}
